package com.kyrioscraft.cloud.security.securitybrowser.session;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kyrioscraft.cloud.security.core.support.SimpleResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author kyrioscraft
 * @Date 2019/1/16 13:41
 * @Description //TODO
 **/
@Slf4j
public class AbstractSessionStrategy {

    private String redirectUrl;

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    private boolean createNewSession = true;

    private ObjectMapper objectMapper = new ObjectMapper();

    public AbstractSessionStrategy(String invalidSessionUrl) {
        Assert.isTrue(UrlUtils.isValidRedirectUrl(invalidSessionUrl),"url must start with '/' or with 'http(s)'");
        this.redirectUrl = invalidSessionUrl;
    }

    protected void onSessionInvalid(HttpServletRequest request, HttpServletResponse response) throws IOException{
        if(createNewSession) {
            request.getSession();
        }

        String sourceUrl = request.getRequestURI();
        String targetUrl;

        if(StringUtils.endsWithIgnoreCase(sourceUrl,".html")) {
            targetUrl = redirectUrl+".html";
            log.info("session失效，跳转到"+targetUrl);
            redirectStrategy.sendRedirect(request,response,targetUrl);
        } else {
            String message = "session已失效";
            if(isConcurrency()) {
                message = message + ",有可能是并发登录导致的";
            }
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(message)));
        }
    }

    protected boolean isConcurrency() {
        return false;
    }

    public void setCreateNewSession(boolean createNewSession) {
        this.createNewSession = createNewSession;
    }
}
